<template>
  <div>
    <van-nav-bar
      title="优惠券"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="coupon-container">
      <div v-if="validCoupons.length === 0">没有可用的优惠券</div>
      <div v-else>
        <div v-for="coupon in validCoupons" :key="coupon.id" class="coupon-card">
          <div class="coupon-info">
            <div class="coupon-name">{{ coupon.name }}</div>
            <div class="coupon-price">￥{{ coupon.price }}</div>
            <div class="coupon-details">
              <div>有效期：{{ formatDate(coupon.expiryDate) }}</div>
              <div>满{{ coupon.minSpend }}元可用</div>
            </div>
          </div>
          <button class="use-button" @click="useCoupon(coupon.id)">立即使用</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { format } from 'date-fns';

const coupons = ref([]);

const today = new Date();
const validCoupons = computed(() => {
  return coupons.value.filter(coupon => new Date(coupon.expiryDate) >= today);
});

const fetchCoupons = async () => {
  try {
    const response = await axios.get('http://localhost:3789/coupon');
    console.log('Fetched coupons:', response.data); // 调试信息
    coupons.value = response.data.data; // 提取 data 部分
  } catch (error) {
    console.error('Failed to fetch coupons:', error);
  }
};

onMounted(() => {
  fetchCoupons();
});

const onClickLeft = () => {
  history.back();
};

const useCoupon = (id: number) => {
  console.log(`使用优惠券 ID: ${id}`);
};

const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'yyyy-MM-dd');
};
</script>

<style scoped>
.coupon-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.coupon-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  transition: transform 0.2s;
}

.coupon-card:hover {
  transform: translateY(-5px);
}

.coupon-info {
  display: flex;
  flex-direction: column;
}

.coupon-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.coupon-price {
  font-size: 24px;
  font-weight: bold;
  color: #e53e3e;
  margin: 10px 0;
}

.coupon-details {
  font-size: 14px;
  color: #888;
}

.use-button {
  background-color: #000;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.use-button:hover {
  background-color: #333;
}
</style>
